package com.kaibes.web.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AdminMenuConfig implements InitializingBean {
    
    @Autowired(required = false)
    private List<AdminMenu> adminMenus;
    
    public List<AdminMenu> getAdminMenus() {
        return adminMenus;
    }

	@Override
	public void afterPropertiesSet() throws Exception {
		if (adminMenus != null) {
            List<AdminMenu> adminMenusTemp = new ArrayList<>();
            Map<String, AdminMenu> menuMap = new HashMap<String, AdminMenu>();
            adminMenus.forEach(menu->{
                if (menu.getKey() != null) {
                    if (menuMap.containsKey(menu.getKey())) {
                        throw new RuntimeException("<"+menu.getName()+">有重复的菜单键值："+menu.getKey());
                    }
                    menuMap.put(menu.getKey(), menu);
                }
                if (menu.getParentKey() == null) {
                    adminMenusTemp.add(menu);
                }
            });
            adminMenus.forEach(menu->{
                if (menu.getParentKey() != null) {
                    AdminMenu parent = menuMap.get(menu.getParentKey());
                    if (parent == null) {
                        throw new RuntimeException("<"+menu.getName()+">有不存在的父菜单："+menu.getParentKey());
                    }
                    
                    menu.setParent(parent);
                    parent.getMenuList().add(menu);
                }
            });
            AdminMenuUtils.sort(adminMenusTemp);
            adminMenus = adminMenusTemp;
        }
	}
    
}
